package com.decade.qiyeshapan;

import com.decade.qiyeshapan.entity.Order;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import java.util.List;
import java.util.Arrays;
import java.util.Map;
import java.util.HashMap;

@SpringBootApplication(scanBasePackages = "com.decade.qiyeshapan")
public class QiyeshapanApplication {

	@Autowired
	private RedisTemplate<String, Object> redisTemplate;

	public static void main(String[] args) {
		SpringApplication.run(QiyeshapanApplication.class, args);
	}

	@Bean
	CommandLineRunner initOrders() {
		return args -> {
			List<Order> orders = Arrays.asList(
				new Order("P1", 100, 50.0, 1, "", 3000.0, 1, 1, "本地"),
				new Order("P1", 150, 45.0, 1, "", 4000.0, 1, 1, "本地"),
				new Order("P1", 80, 60.0, 1, "", 3500.0, 1, 1, "本地"),
				new Order("P1", 200, 40.0, 1, "", 5000.0, 1, 1, "本地"),
				new Order("P1", 120, 55.0, 1, "", 4500.0, 1, 1, "本地")
			);

			orders.forEach(order -> {
				String key = "order:" + order.getOrderId();
				if (!redisTemplate.hasKey(key)) {
					redisTemplate.opsForHash().putAll(key, convertOrderToMap(order));
				}
			});
			System.out.println("初始化5个订单完成（Hash结构）");
		};
	}

	private Map<String, Object> convertOrderToMap(Order order) {
		Map<String, Object> map = new HashMap<>();
		map.put("orderId", order.getOrderId());
		map.put("product", order.getProduct());
		map.put("quantity", order.getQuantity());
		map.put("unitPrice", order.getUnitPrice());
		map.put("totalAmount", order.getTotalAmount());
		map.put("paymentTerm", order.getPaymentTerm());
		map.put("isoCertification", order.getIsoCertification());
		map.put("cost", order.getCost());
		map.put("profit", order.getProfit());
		map.put("year", order.getYear());
		map.put("quarter", order.getQuarter());
		map.put("region", order.getRegion());
		return map;
	}

}
